import React, { useEffect, useState } from "react";
import classnames from 'classnames';
import Style from './index.module.less';
import TextIcon from '../TextIcon';

import { Input, HighlightOption, Popup } from 'tdesign-react';
import '@amap/amap-jsapi-types';
import { randomKey, amapAddressToMyAddress, amapPromise } from 'utils/common';
import request from "../../utils/request";

let timer: ReturnType<typeof setTimeout>;

const FuzzyAddressInput = (props: {
  type: string;
  onChange: (v: any) => {};
  value: { address_name: string; detailAddress: string };
}) => {
  const [title, setTitle] = useState(props.value.address_name || '');
  const [detailAddress, setDetailAddress] = useState('');
  const [tips, setTips] = useState<any[]>([]);
  useEffect(() => {
    setTitle(props.value.address_name || '');
  }, [props.value]);
  const onSelect = (val) => {
    console.log('auto complete selected:', val);
    setTitle(val.name);
    console.log('detail address', val.district + val.address);
    setDetailAddress(val.district + val.address);
    props.onChange(amapAddressToMyAddress(val)); // 把省市区街道 经纬度
  };
  // 输入框内容发生变化时进行搜索，200ms 搜索一次
  const onChange = (val) => {
    if (!val) return ;
    // setTitle(val);
    clearTimeout(timer);
    timer = setTimeout(() => {
      amapPromise.then((AMap) => {
        const autoOptions = {
          city: '全国',
        };
        const autoComplete = new AMap.AutoComplete(autoOptions);
        autoComplete.search(val, (status, result) => {
          // 搜索成功时，result即是对应的匹配数据
          console.log(status, result);
          const tipsRaw = result?.tips || [];
          setTips(tipsRaw);
          clearTimeout(timer);
        });
      });
    }, 200);
  };
  return (
    <Popup
      trigger='focus'
      overlayInnerStyle={{ maxHeight: 388, overflowY: 'auto', padding: '6px 0' }}
      overlayClassName={Style.customPopup}
      content={
        <div>
          {tips.map((item) => (
            <div
              className={Style.customOption}
              key={randomKey()}
              onClick={() => {
                onSelect(item);
              }}
            >
              <div className='custom-option__main'>
                {/* {item?.name || ''} */}
                <HighlightOption content={item?.name} keyword={title} />
                <small className='description'>
                  {item?.district}
                  {item?.address}
                </small>
              </div>
            </div>
          ))}
        </div>
      }
      placement='bottom-left'
    >
      <div className={classnames(Style.container)}>
        <div className={classnames(Style.iconContainer)}>
          <TextIcon type={props.type}></TextIcon>
        </div>
        {/* <StartIcon></StartIcon> */}
        <Input
          placeholder='请选择省市区（必填）'
          value={title}
          onChange={(val) => {
            setTitle(val);
            if (val) {
              onChange(val);
            }
          }}
        />
        <div className={classnames(Style.detail)}>{detailAddress || props.value.detailAddress}</div>
      </div>
    </Popup>
  );
};

FuzzyAddressInput.displayName = 'FuzzyAddressInput';

export default FuzzyAddressInput;
